package top.goldenyear.porpoise.common.core.util.solon;

import org.noear.solon.Solon;
import org.noear.solon.core.handle.Context;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

public class SolonUtils {

  /**
   * 获取完整的请求路径，包括：域名，端口，上下文访问路径
   *
   * @return 服务地址
   */
  public static String getUrl() {
    Context current = Context.current();
    StringBuilder url = new StringBuilder(current.url());
    String contextPath = Solon.cfg().serverContextPath();
    return url.delete(url.length() - current.path().length(), url.length()).append(contextPath).toString();
  }

  /**
   * 获取 Bean
   *
   * @param type 类型
   */
  public static <T> T getBean(Class<T> type) {
    return Solon.context().getBean(type);
  }

  /**
   * 获取 Bean
   *
   * @param type 类型
   */
  public static <T> Map<String, T> getBeansMap(Class<T> type) {
    return Solon.context().getBeansMapOfType(type);
  }


  /**
   * 获取 Bean
   *
   * @param type 类型
   */
  public static <T> List<T> getBeans(Class<T> type) {
    return Solon.context().getBeansOfType(type);
  }

  /**
   * 获取 Bean
   *
   * @param name 名字
   */
  public static <T> T getBean(String name) {
    return Solon.context().getBean(name);
  }

  public static <T>  void getBeanAsync(String name, Consumer<T> callback) {
    Solon.context().getBeanAsync(name, callback);
  }

  public static <T> void getBeanAsync(Class<T> type, Consumer<T> callback) {
    Solon.context().getBeanAsync(type, callback);
  }

  /**
   * 获取属性
   */
  public static String getProps(String key) {
    return Solon.cfg().get(key);
  }

}
